package com.yzdbx.individualtask;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.yzdbx.utils.DbUtil;
import com.yzdbx.utils.GenUtil;

import java.math.BigDecimal;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

public class AfterSaleReGen {
    public static void main(String[] args) throws Exception {
        // 处理日期参数
        String startDate = null;
        String endDate = null;
        
        if (args.length >= 2) {
            startDate = args[0];
            endDate = args[1];
            System.out.println("指定生成日期范围: " + startDate + " 到 " + endDate);
        } else if (args.length == 1) {
            startDate = args[0];
            endDate = args[0];
            System.out.println("指定生成日期: " + startDate);
        } else {
            System.out.println("未指定日期，将生成所有销售订单的售后工单数据");
        }
        
        // 初始化 GenUtil 的日期信息
        LocalDate currentDate = LocalDate.now();
        if (startDate != null) {
            currentDate = LocalDate.parse(startDate);
        }
        GenUtil.setCurDate(currentDate);
        GenUtil.setCurTimeStamp(new Timestamp(currentDate.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli()));
        
        Connection connection = DbUtil.getConnection();
        boolean originalAutoCommit = true;
        
        try {
            originalAutoCommit = connection.getAutoCommit();
            connection.setAutoCommit(false);

            // 查询销售订单ID（根据日期过滤）
            List<Integer> orderIds = new ArrayList<>();
            String orderQuery;
            PreparedStatement stmt;
            
            if (startDate != null && endDate != null) {
                if (startDate.equals(endDate)) {
                    // 单个日期
                    orderQuery = "SELECT id FROM whmskj_YH5GGC.salesOrders WHERE DATE(dateOfOrder) = ?";
                    stmt = connection.prepareStatement(orderQuery);
                    stmt.setString(1, startDate);
                } else {
                    // 日期范围
                    orderQuery = "SELECT id FROM salesOrders WHERE DATE(dateOfOrder) BETWEEN ? AND ?";
                    stmt = connection.prepareStatement(orderQuery);
                    stmt.setString(1, startDate);
                    stmt.setString(2, endDate);
                }
            } else {
                // 所有日期
                orderQuery = "SELECT id FROM salesOrders";
                stmt = connection.prepareStatement(orderQuery);
            }
            
            ResultSet rs = stmt.executeQuery();
            while (rs.next()) {
                orderIds.add(rs.getInt("id"));
            }
            rs.close();
            stmt.close();

            if (CollectionUtil.isEmpty(orderIds)) {
                if (startDate != null && endDate != null) {
                    if (startDate.equals(endDate)) {
                        System.out.println("没有找到 " + startDate + " 日期的销售订单数据，无法生成售后工单数据！");
                    } else {
                        System.out.println("没有找到 " + startDate + " 到 " + endDate + " 日期范围的销售订单数据，无法生成售后工单数据！");
                    }
                } else {
                    System.out.println("没有找到销售订单数据，无法生成售后工单数据！");
                }
                return;
            }

            System.out.println("找到 " + orderIds.size() + " 条销售订单，开始生成售后工单数据...");

            // 售后工单生成逻辑（完全参考原有逻辑）
            Map<Integer, LinkedHashMap<String, Object>> clientMap = DbUtil.resultSetToList(connection.prepareStatement("select * from  jcClientInformation").executeQuery())
                    .stream().collect(Collectors.toMap(cur -> (int) cur.get("id"), cur -> cur));

            List<LinkedHashMap<String, Object>> saleOrders = DbUtil.resultSetToList(connection.prepareStatement("select  * from salesOrders").executeQuery())
                    .stream().filter(cur -> orderIds.contains(((int) cur.get("id")))).toList();

            // 售后工单相关列表（参考原有逻辑）
            List<String> firstList = Arrays.asList(
                    "请协助核查生产批次并反馈根本原因分析报告",
                    "经初步判断属于工艺瑕疵，请车间质量部在24小时内处理",
                    "请对照质检标准确认是否属于出厂前漏检情况",
                    "退货品已返回工厂仓库，请车间48小时内完成处理",
                    "明确发货产品质量问题，请马上核查问题原因尽快处理"
            );

            List<String> secondList = Arrays.asList(
                    "问题已经处理，已经发货给客户",
                    "次品已经按要求都维修好",
                    "设备参数有误，已经调整处理客户问题",
                    "货品已装车出库，预计今天到客户工厂",
                    "规格生产错误，已经返工重新加工"
            );

            int num = 0;
            int afterSaleId = getMaxId(connection, "aftersalesWork");
            int postSaleDetailId = getMaxId(connection, "postsaleList");
            int detailsOfPostsaleWorkOrdersId = getMaxId(connection, "detailsOfPostsaleWorkOrders");
            
            // 按日期分组的售后工单号计数器
            Map<String, Integer> dateCounterMap = new HashMap<>();
            
            for (LinkedHashMap<String, Object> saleOrder : saleOrders) {
                // 百分之30的几率生成售后（参考原有逻辑）
                if (RandomUtil.randomInt(100) > 30) {
                    System.out.println("跳过销售订单 " + saleOrder.get("id") + "（未命中30%概率）");
                    continue;
                }
                
                num++;
                System.out.println("正在处理第 " + num + " 个售后工单，销售订单ID: " + saleOrder.get("id"));
                
                // 获取销售订单的订单日期
                java.sql.Date orderDate = (java.sql.Date) saleOrder.get("dateOfOrder");
                Timestamp orderTimestamp = new Timestamp(orderDate.getTime());
                
                // 设置当前日期为订单日期，确保工单号生成正确
                GenUtil.setCurDate(orderDate.toLocalDate());
                GenUtil.setCurTimeStamp(orderTimestamp);
                
                // 按日期分组的售后工单号生成逻辑
                String dateKey = orderDate.toString();
                int currentCount = dateCounterMap.getOrDefault(dateKey, 0) + 1;
                dateCounterMap.put(dateKey, currentCount);
                
                // 生成售后工单号（完全按照原有逻辑）
                String workOrderNumber = GenUtil.getNo("SH", currentCount);
                System.out.println("生成售后工单号: " + workOrderNumber);
                
                // 创建售后工单主表记录（完全按照原有逻辑）
                int clientId = (int) saleOrder.get("clientInformation");
                LinkedHashMap<String, Object> client = clientMap.get(clientId);
                
                try {
                    PreparedStatement statement = connection.prepareStatement("insert into aftersalesWork(id,postsaleWorkOrderNumber,associatedSalesOrders,client,otherOrganiser,contactCall,dateOfFeedback,typeOfProblem,processStatus,remarks)values (?,?,?,?,?,?,?,?,?,?)");
                    statement.setInt(1, ++afterSaleId);
                    statement.setString(2, workOrderNumber);
                    statement.setInt(3, (int) saleOrder.get("id"));
                    statement.setInt(4, clientId);
                    statement.setString(5, (client.get("otherOrganiser1").toString()));
                    statement.setString(6, ObjectUtil.isNotNull(client.get("contactDetails"))?client.get("contactDetails").toString():"/");
                    statement.setDate(7, orderDate);
                    statement.setString(8, RandomUtil.randomEle(Arrays.asList("质量问题","工艺问题","其他问题")));
                    statement.setString(9, "已完结");
                    statement.setString(10, "加急处理");
                    
                    System.out.println("准备插入售后工单，参数：ID=" + afterSaleId + ", 工单号=" + workOrderNumber + ", 销售订单ID=" + saleOrder.get("id"));
                    int result = statement.executeUpdate();
                    System.out.println("售后工单主表记录创建成功，ID: " + afterSaleId + ", 影响行数: " + result);
                    
                    // 立即提交事务
                    connection.commit();
                    
                } catch (Exception e) {
                    System.err.println("插入售后工单失败: " + e.getMessage());
                    e.printStackTrace();
                    connection.rollback();
                    throw e;
                }

                // 查询销售订单详情
                PreparedStatement detailStatement = connection.prepareStatement("select * from xs02SalesOrderBreakdown where associatedSalesOrders=?");
                detailStatement.setInt(1, (int) saleOrder.get("id"));
                List<LinkedHashMap<String, Object>> maps = DbUtil.resultSetToList(detailStatement.executeQuery());
                System.out.println("找到 " + maps.size() + " 条销售订单明细");
                
                for (LinkedHashMap<String, Object> map : maps) {
                    PreparedStatement detailInsertStatement = connection.prepareStatement("insert into postsaleList(id,f8ca,productInformation,numberAfterSale,quantityOfShipments)values (?,?,?,?,?)");
                    detailInsertStatement.setInt(1, ++postSaleDetailId);
                    detailInsertStatement.setInt(2, afterSaleId);
                    detailInsertStatement.setInt(3, (int) map.get("productInformation"));
                    BigDecimal quantity = (BigDecimal) map.get("quantityOfShipments");
                    detailInsertStatement.setBigDecimal(5, quantity);
                    detailInsertStatement.setBigDecimal(4, RandomUtil.randomBigDecimal(BigDecimal.ZERO, quantity.add(BigDecimal.ONE)).setScale(2, BigDecimal.ROUND_HALF_UP));
                    detailInsertStatement.execute();
                }
                System.out.println("售后明细记录创建成功，共 " + maps.size() + " 条");

                // 服务明细1
                PreparedStatement serviceStatement1 = connection.prepareStatement("insert into detailsOfPostsaleWorkOrders(id,otherOrganiser1,otherOrganiser2,positions,associatedPostsaleWorksheets,communicationDescription,time)values (?,?,?,?,?,?,?)");
                serviceStatement1.setInt(1, ++detailsOfPostsaleWorkOrdersId);
                serviceStatement1.setString(2, (client.get("otherOrganiser1").toString()));
                serviceStatement1.setString(3,ObjectUtil.isNotNull(client.get("contactDetails"))?client.get("contactDetails").toString():"/");
                serviceStatement1.setString(4, "");
                serviceStatement1.setInt(5, afterSaleId);
                serviceStatement1.setString(6, RandomUtil.randomEle(firstList));
                long dayOfMs = new SimpleDateFormat("yyyy-MM-dd").parse(orderDate.toString()).getTime();
                Timestamp firstTime = new Timestamp(RandomUtil.randomLong(dayOfMs+9*60*60*1000,dayOfMs+17*60*60*1000));
                serviceStatement1.setTimestamp(7, firstTime);
                serviceStatement1.execute();

                // 服务明细2
                PreparedStatement serviceStatement2 = connection.prepareStatement("insert into detailsOfPostsaleWorkOrders(id,otherOrganiser1,otherOrganiser2,positions,associatedPostsaleWorksheets,communicationDescription,time)values (?,?,?,?,?,?,?)");
                serviceStatement2.setInt(1, ++detailsOfPostsaleWorkOrdersId);
                serviceStatement2.setString(2, (client.get("otherOrganiser1").toString()));
                serviceStatement2.setString(3, ObjectUtil.isNotNull(client.get("contactDetails"))?client.get("contactDetails").toString():"/");
                serviceStatement2.setString(4, "");
                serviceStatement2.setInt(5, afterSaleId);
                serviceStatement2.setString(6, RandomUtil.randomEle(secondList));
                serviceStatement2.setTimestamp(7, new Timestamp(firstTime.getTime() + RandomUtil.randomInt(2 * 60 * 60 * 1000)));
                serviceStatement2.execute();
                
                System.out.println("服务明细记录创建成功，共 2 条");
                System.out.println("---");
            }

            if (startDate != null && endDate != null) {
                if (startDate.equals(endDate)) {
                    System.out.println(startDate + " 日期的售后工单数据生成完成！共生成 " + num + " 条售后工单记录");
                } else {
                    System.out.println(startDate + " 到 " + endDate + " 日期范围的售后工单数据生成完成！共生成 " + num + " 条售后工单记录");
                }
            } else {
                System.out.println("售后工单数据生成完成！共生成 " + num + " 条售后工单记录");
            }
            
        } finally {
            try {
                connection.setAutoCommit(originalAutoCommit);
            } catch (SQLException ignore) {}
            DbUtil.closeConnection(connection);
        }
    }

    private static int getMaxId(Connection connection, String table) throws SQLException {
        try (Statement stmt = connection.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT MAX(id) FROM " + table)) {
            if (rs.next()) {
                return rs.getInt(1);
            }
        }
        return 0;
    }
}